package com.xiaoxie.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class RateLimitController {

    @GetMapping("/rateLimit/byUrl")
    public String byUrl() {
        return "按rest地址限流测试";
    }

    @GetMapping("/rateLimit/byResource")
    @SentinelResource(value = "byResourceSentinelResource",
            blockHandler = "handleException", blockHandlerClass = FallbackHandler.class)
    public String byResource() {
        return "按资源名称SentinelResource限流测试";
    }

    /*private String handleException(BlockException exception) {
        return "服务不可用 @SentinelResource启动" + "\t" + "请稍后再试！";
    }*/

    @GetMapping("/rateLimit/doAction/{p1}")
    @SentinelResource(value = "doActionSentinelResource",
            blockHandlerClass = FallbackHandler.class,
            blockHandler = "handleActionException",
            fallbackClass = FallbackHandler.class,
            fallback = "handleActionFallback")
    public String doAction(@PathVariable("p1") Integer p1) {
        if(p1 == 0) {
            throw new RuntimeException("参数异常,不可以为0");
        }
        return "doAction" + "\t" + p1;
    }


    /**
     * 热点参数限流
     * @param p1
     * @param p2
     * @return
     */
    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey",blockHandler = "delHandler_testHotKey")
    public String testHotKey(@RequestParam(value = "p1", required = false) String p1,
                             @RequestParam(value = "p2", required = false) String p2) {
        return "------testHotKey";
    }
    private String delHandler_testHotKey(String p1, String p2, BlockException exception) {
        return "------dealHandler_testHotKey";
    }


}
